package com.micro.ai.files.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.files.entity.FileVersion;
import com.micro.ai.files.mapper.FileVersionMapper;
import com.micro.ai.files.service.FileVersionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 文件版本服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class FileVersionServiceImpl extends ServiceImpl<FileVersionMapper, FileVersion> implements FileVersionService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FileVersion create(FileVersion version) {
        if (version == null) {
            throw new BusinessException("F0000", "文件版本信息不能为空");
        }
        
        if (!StringUtils.hasText(version.getFileId())) {
            throw new BusinessException("F0000", "文件ID不能为空");
        }
        
        // 获取当前最大版本号
        Integer maxVersion = getMaxVersionNumber(version.getFileId());
        if (maxVersion == null) {
            maxVersion = 0;
        }
        
        version.setVersionNumber(maxVersion + 1);
        version.setCreatedAt(LocalDateTime.now());
        
        boolean success = this.save(version);
        if (!success) {
            throw new BusinessException("F0003", "创建文件版本失败");
        }
        
        log.info("创建文件版本成功: versionId={}, fileId={}, versionNumber={}", 
                version.getId(), version.getFileId(), version.getVersionNumber());
        return version;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("F0000", "版本ID不能为空");
        }
        
        FileVersion version = this.getById(id);
        if (version == null) {
            throw new BusinessException("F0002", "文件版本不存在: " + id);
        }
        
        boolean success = this.removeById(id);
        if (!success) {
            throw new BusinessException("F0003", "删除文件版本失败");
        }
        
        log.info("删除文件版本成功: versionId={}, fileId={}", id, version.getFileId());
    }

    @Override
    public Page<FileVersion> pageQuery(int pageNum, int pageSize, String fileId) {
        if (pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize < 1 || pageSize > 100) {
            pageSize = 20;
        }
        
        Page<FileVersion> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<FileVersion> query = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(fileId)) {
            query.eq(FileVersion::getFileId, fileId);
        }
        
        query.orderByDesc(FileVersion::getVersionNumber);
        
        return this.page(page, query);
    }

    @Override
    public List<FileVersion> listByFileId(String fileId) {
        LambdaQueryWrapper<FileVersion> query = new LambdaQueryWrapper<>();
        query.eq(FileVersion::getFileId, fileId)
             .orderByDesc(FileVersion::getVersionNumber);
        
        return this.list(query);
    }

    @Override
    public FileVersion getLatestVersion(String fileId) {
        LambdaQueryWrapper<FileVersion> query = new LambdaQueryWrapper<>();
        query.eq(FileVersion::getFileId, fileId)
             .orderByDesc(FileVersion::getVersionNumber)
             .last("LIMIT 1");
        
        return this.getOne(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void restoreVersion(String versionId) {
        if (!StringUtils.hasText(versionId)) {
            throw new BusinessException("F0000", "版本ID不能为空");
        }
        
        FileVersion version = this.getById(versionId);
        if (version == null) {
            throw new BusinessException("F0002", "文件版本不存在: " + versionId);
        }
        
        // 创建新版本，使用恢复的版本内容
        FileVersion newVersion = new FileVersion();
        newVersion.setFileId(version.getFileId());
        newVersion.setFilePath(version.getFilePath());
        newVersion.setFileSize(version.getFileSize());
        newVersion.setFileHash(version.getFileHash());
        newVersion.setMimeType(version.getMimeType());
        newVersion.setChangeDescription("恢复版本 " + version.getVersionNumber());
        newVersion.setCreatedBy(version.getCreatedBy());
        
        create(newVersion);
        
        log.info("恢复文件版本成功: versionId={}, fileId={}", versionId, version.getFileId());
    }

    /**
     * 获取最大版本号
     */
    private Integer getMaxVersionNumber(String fileId) {
        LambdaQueryWrapper<FileVersion> query = new LambdaQueryWrapper<>();
        query.eq(FileVersion::getFileId, fileId)
             .select(FileVersion::getVersionNumber)
             .orderByDesc(FileVersion::getVersionNumber)
             .last("LIMIT 1");
        
        FileVersion version = this.getOne(query);
        return version != null ? version.getVersionNumber() : null;
    }
}

